import React, { useEffect, useRef, useState } from "react";
import * as THREE from "three";
import { AudioOutlined } from "@ant-design/icons";
// 导入必要的组件和图标
const styles = document.createElement("style");
styles.textContent = `
  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
`;
document.head.appendChild(styles);
import { Button, Input, message, List, Avatar, Popover } from "antd";
import { SmileOutlined } from "@ant-design/icons";
import axios from "axios"; // 添加这行导入Axios
import { FBXLoader } from "three/examples/jsm/loaders/FBXLoader";
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
import ThreeAvatar from "../../components/ThreeAvatar";
import style from "./index.module.scss";
import { useTranslation } from "react-i18next";
import i18n from "../../locale/i18n";
import icon1 from "../../../public/answer-model.svg";
import icon11 from "../../../public/answer-icon.svg";
import icon2 from "../../../public/chat-model.svg";
import icon22 from "../../../public/chat-model-active.svg";
import icon3 from "../../../public/night-model.svg";
import icon33 from "../../../public/day-model.svg";
import { SendOutlined, UserOutlined } from "@ant-design/icons";
const FBX_PATH = "/modules/shuzi.glb"; // 修改模型路径
import Barrage from "../../components/Barrage"; // 导入弹幕组件
// Numpeo 组件定义，用于渲染数字人页面
// 正确示例：所有Hooks都在组件顶层调用
const Numpeo: React.FC = () => {
  // 国际化
  const { t } = useTranslation();
  // 定义动作选项
  const mountRef = useRef<HTMLDivElement>(null);
  const [isSpeend, setIsSpeend] = useState<boolean>(true);

  const [isSpeend1, setIsSpeend1] = useState<boolean>(false);
  const [isSpeend2, setIsSpeend2] = useState<boolean>(false);
  const [isSpeend3, setIsSpeend3] = useState<boolean>(false);
  // 添加动作选择状态
  const [selectedAction, setSelectedAction] = useState("idle");
  const [flag, setFlag] = useState<boolean>(false);
  const cameraRef = useRef<THREE.PerspectiveCamera>(null);
  const rendererRef = useRef<THREE.WebGLRenderer>(null);
  const [flagshow, setFlagshow] = useState(true);
  // 定义动作选项
  useEffect(() => {
    let mixer: THREE.AnimationMixer | null = null;
    let frameId: number;
    const scene = new THREE.Scene();
    const camera = new THREE.PerspectiveCamera(45, 1, 0.1, 1000);
    camera.position.set(0, 1.5, 3);
    cameraRef.current = camera;

    const renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true });
    renderer.setSize(400, 500);
    rendererRef.current = renderer;
    if (mountRef.current) {
      mountRef.current.appendChild(renderer.domElement);
      // 添加鼠标滚轮缩放事件
      const handleWheel = (event: WheelEvent) => {
        event.preventDefault();
        if (!cameraRef.current) return;

        // 根据滚轮方向调整相机距离
        const delta = event.deltaY > 0 ? 0.2 : -0.2;
        const newZ = cameraRef.current.position.z + delta;

        // 限制缩放范围
        if (newZ > 1) {
          // 仅保留下限检查，移除newZ < 10的上限限制
          cameraRef.current.position.z = newZ;
          // 使用cameraRef.current而非camera变量
          if (cameraRef.current) {
            renderer.render(scene, cameraRef.current);
          }
        }
      };

      renderer.domElement.addEventListener("wheel", handleWheel);

      // 清理事件监听
      return () => {
        renderer.domElement.removeEventListener("wheel", handleWheel);
      };
    }

    // 灯光
    const light = new THREE.DirectionalLight(0xffffff, 1);
    light.position.set(0, 5, 5);
    scene.add(light);
    scene.add(new THREE.AmbientLight(0xffffff, 0.5));

    // 加载FBX模型
    const loader = new GLTFLoader();
    loader.load(
      FBX_PATH,
      (gltf) => {
        const object = gltf.scene;
        scene.add(object);
        // 添加缩放代码，将模型缩小一倍
        object.scale.set(0.5, 0.5, 0.5); // 1→0.5表示缩小50%
        if (gltf.animations && gltf.animations.length > 0) {
          mixer = new THREE.AnimationMixer(object);
          mixer.clipAction(gltf.animations[0]).play();
        }
      },
      undefined,
      (error: any) => {
        // eslint-disable-next-line no-console
        console.error("FBX模型加载失败", error);
      }
    );

    const animate = () => {
      frameId = requestAnimationFrame(animate);
      if (mixer) mixer.update(0.016);
      // 使用cameraRef.current而非初始camera变量
      if (cameraRef.current) {
        renderer.render(scene, cameraRef.current);
      }
    };
    animate();

    return () => {
      cancelAnimationFrame(frameId);
      renderer.dispose();
      if (
        mountRef.current &&
        renderer.domElement.parentNode === mountRef.current
      ) {
        mountRef.current.removeChild(renderer.domElement);
      }
    };
  }, []);

  // 切换主题函数
  const changezhuti = () => {
    setIsSpeend(!isSpeend);
  };
  const changelanguge = () => {
    i18n.changeLanguage(i18n.language === "zh" ? "en" : "zh");
  };
  // 渲染Numpeo页面

  const changesicon1 = () => {
    setIsSpeend1(!isSpeend1);
    setFlagshow(!flagshow);
  };
  const changesicon2 = () => {
    setIsSpeend2(!isSpeend2);
    setFlag(!flag);
  };
  const changesicon3 = () => {
    setIsSpeend3(!isSpeend3);
    setIsSpeend(!isSpeend);
  };
  const videoRef = useRef<HTMLVideoElement>(null);
  const [videoSize, setVideoSize] = useState({ width: 0, height: 0 });

  // 添加视频尺寸监听
  useEffect(() => {
    const updateVideoSize = () => {
      if (videoRef.current) {
        setVideoSize({
          width: videoRef.current.offsetWidth,
          height: videoRef.current.offsetHeight,
        });
      }
    };

    // 初始获取尺寸
    updateVideoSize();
    // 监听窗口大小变化
    window.addEventListener("resize", updateVideoSize);
    return () => window.removeEventListener("resize", updateVideoSize);
  }, []);

  const [messages, setMessages] = useState<
    {
      id: string;
      content: string;
      role: "user" | "ai";
    }[]
  >([]);
  const [inputText, setInputText] = useState("");
  const messageEndRef = useRef<HTMLDivElement>(null);
  const getAIResponse = async (userMessage: string) => {
    try {
      const response = await axios.post(
        "https://api.moonshot.cn/v1/chat/completions",
        {
          model: "moonshot-v1-8k", // 根据豆包API文档选择合适的模型
          messages: [
            { role: "system", content: "你是豆包，一个智能助手。" },
            { role: "user", content: userMessage },
          ],
          temperature: 0.7,
        },
        {
          headers: {
            "Content-Type": "application/json",
            Authorization:
              "Bearer sk-fftBI7yZWo4hCPyXFJQ2Bb5d85vLJoHrb4aDxuKfZ7O1itun", // 替换为你的API密钥
          },
        }
      );

      // 解析API响应
      if (
        response.data &&
        response.data.choices &&
        response.data.choices.length > 0
      ) {
        return response.data.choices[0].message.content;
      } else {
        return "抱歉，我无法生成回复。";
      }
    } catch (error) {
      console.error("调用豆包API出错:", error);
      return "抱歉，请求过程中出现错误。";
    }
  };
  const handleSendMessage = async () => {
    if (!inputText.trim()) return;

    // 添加用户消息
    const userMessage = {
      id: Date.now().toString(),
      content: inputText,
      role: "user" as const,
    };
    setInputText("");

    // 先添加用户消息到列表
    setMessages((prev) => [...prev, userMessage]);

    // 添加加载状态的AI消息
    const loadingMessageId = Date.now().toString() + "loading";
    const loadingMessage = {
      id: loadingMessageId,
      content: "",
      role: "ai" as const,
      isLoading: true,
    };
    setMessages((prev) => [...prev, loadingMessage]);

    try {
      // 获取AI响应
      const aiResponse = await getAIResponse(inputText);
      // 替换加载消息为实际AI响应
      setMessages((prev) =>
        prev.map((msg) =>
          msg.id === loadingMessageId
            ? {
                ...msg,
                content: aiResponse,
                isLoading: false,
              }
            : msg
        )
      );
    } catch (error) {
      console.error("处理AI响应出错:", error);
      message.error("获取AI回复失败");
      // 移除加载消息
      setMessages((prev) => prev.filter((msg) => msg.id !== loadingMessageId));
    }
  };

  // 自动滚动到底部
  useEffect(() => {
    messageEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages]);
  // 正确：effect hook在顶层作用域
  // 删除下面这行多余的闭合括号
  // }
  const [isListening, setIsListening] = useState(false);
  const recognitionRef = useRef<SpeechRecognition | null>(null);
  // 添加表情包相关状态
  const [showEmojiPanel, setShowEmojiPanel] = useState(false);

  // 表情包数据
  const emojis = [
    "😀",
    "😃",
    "😄",
    "😁",
    "😆",
    "😅",
    "😂",
    "🤣",
    "😊",
    "😇",
    "🙂",
    "🙃",
    "😉",
    "😌",
    "😍",
    "🥰",
    "😘",
    "😗",
    "😙",
    "😚",
    "😋",
    "😛",
    "😝",
    "😜",
    "🤪",
    "🤨",
    "🧐",
    "🤓",
    "😎",
    "🤩",
  ];

  // 添加表情到输入框函数
  const addEmojiToInput = (emoji: string) => {
    setInputText((prev) => prev + emoji);
    setShowEmojiPanel(false);
  };
  const toggleVoiceRecognition = () => {
    // 检查浏览器支持
    if (
      !"SpeechRecognition" in window &&
      !"webkitSpeechRecognition" in window
    ) {
      message.error("您的浏览器不支持语音识别功能");
      return;
    }

    const SpeechRecognition =
      window.SpeechRecognition || window.webkitSpeechRecognition;
    if (!recognitionRef.current) {
      recognitionRef.current = new SpeechRecognition();
      recognitionRef.current.lang = "zh-CN"; // 设置中文识别
      recognitionRef.current.interimResults = false;
      recognitionRef.current.maxAlternatives = 1;

      // 识别结果处理
      recognitionRef.current.onresult = (event) => {
        const transcript = event.results[0][0].transcript;
        setInputText(transcript);
        setIsListening(false);
        // 自动发送消息
        if (transcript.trim()) {
          handleSendMessage();
        }
      };

      // 错误处理
      recognitionRef.current.onerror = (event) => {
        console.error("语音识别错误:", event.error);
        setIsListening(false);
        message.error("语音识别失败，请重试");
      };

      // 结束处理
      recognitionRef.current.onend = () => {
        if (isListening) {
          recognitionRef.current?.start(); // 如果仍在监听状态，继续识别
        }
      };
    }

    // 切换识别状态
    if (isListening) {
      recognitionRef.current.stop();
      setIsListening(false);
    } else {
      recognitionRef.current.start();
      setIsListening(true);
      message.info("开始语音识别...");
    }
  };
  return (
    <div
      className={style.container}
      style={{ height: "100vh", background: "#f8faff" }}
    >
      {/* 顶部叠加图片 */}

      {/* 主体内容：左侧数字人，右侧原有内容 */}
      <div
        className={style[`${isSpeend ? "bottom-day" : "bottom-night"}`]}
        style={{
          height: "100vh",
        }}
      >
        <div
          className={style[`${isSpeend ? "night-theme" : "day-theme"}`]}
          style={{
            width: "100%",
            position: "relative",
            height: 80,
            marginBottom: 16,
          }}
        >
          <div style={{ position: "absolute", top: 10, right: 200 }}>
            <Button style={{ margin: "0 10px" }} onClick={changezhuti}>
              {t("切换主题")}
            </Button>
            <Button style={{ margin: "0 10px" }}>{t("进入3D")}</Button>
            <Button style={{ margin: "0 10px" }} onClick={changelanguge}>
              {t("中英文切换")}
            </Button>
          </div>
        </div>
        <div>
          <div
            style={{
              display: "flex",
              flexDirection: "row",
              alignItems: "center",
              justifyContent: "space-between",
              width: "100%",
            }}
          >
            {/* 左侧数字人 */}
            <div style={{ marginLeft: 0 }}>
              <div style={{ margin: "20px" }}>
                <label className={style[`${isSpeend ? "sp1" : "sp2"}`]}>
                  动作:
                </label>
                <select
                  value={selectedAction}
                  onChange={(e) => setSelectedAction(e.target.value as any)}
                  style={{ marginLeft: "10px", padding: "5px" }}
                >
                  <option value="idle">默认</option>
                  <option value="沮丧">沮丧</option>
                  {/* <option value="开心">开心</option> */}
                  <option value="运动">运动</option>
                  <option value="打招呼">打招呼</option>
                </select>
              </div>
              <ThreeAvatar currentAction={selectedAction} />
            </div>
            {/* 右侧原有内容 */}
            <div
              className={style[`${isSpeend ? "midrightday" : "midrightdays"}`]}
              style={{
                width: 1000,
                height: 600,
                borderRadius: 8,
                marginRight: 50,
                marginTop: 50,
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                position: "relative", // 添加相对定位
              }}
            >
              <div
                style={{
                  margin: "auto",
                  width: "90%",
                  height: "90%",
                  objectFit: "contain",
                  borderRadius: 4,
                  background: "#fff",
                  display: flagshow ? "none" : "block",
                  flexDirection: "column",
                  padding: "16px",
                  overflow: "hidden",
                }}
              >
                {/* 聊天标题 */}
                <div
                  style={{
                    fontSize: "18px",
                    fontWeight: "bold",
                    padding: "12px 0",
                    color: "#333",
                    textAlign: "center",
                    position: "sticky",
                    top: 0,
                    backgroundColor: "#fff",
                    zIndex: 1,
                  }}
                >
                  智能助手
                </div>

                {/* 聊天消息列表 */}
                <div
                  style={{
                    flex: 1,
                    height: "400px",
                    overflowY: "auto",
                    padding: "8px",
                    backgroundColor: "#f5f5f5",
                    borderRadius: 4,
                  }}
                >
                  <List
                    dataSource={messages}
                    split={false} // 添加此行禁用分隔线
                    renderItem={(item, index) => (
                      <List.Item
                        key={index}
                        style={{
                          justifyContent:
                            item.role === "user" ? "flex-end" : "flex-start",
                          marginBottom: "8px",
                          display: "flex",
                          alignItems: "center",
                        }}
                      >
                        {/* AI头像放在消息左侧 */}
                        {item.role !== "user" && (
                          <Avatar
                            src=""
                            style={{
                              marginRight: "8px",
                              backgroundColor: "#f5f5f5",
                            }}
                          />
                        )}

                        {/* 消息气泡 */}
                        <div
                          style={{
                            maxWidth: "70%",
                            padding: "10px 14px",
                            borderRadius: "18px",
                            boxShadow: "0 1px 3px rgba(0, 0, 0, 0.1)",
                            backgroundColor:
                              item.role === "user" ? "#1890ff" : "#fff",
                            color: item.role === "user" ? "#fff" : "#333",
                          }}
                        >
                          {item.isLoading ? (
                            <div
                              style={{
                                display: "flex",
                                alignItems: "center",
                                gap: "8px",
                              }}
                            >
                              <div
                                className="loader"
                                style={{
                                  width: "16px",
                                  height: "16px",
                                  border: "2px solid #f3f3f3",
                                  borderTop: "2px solid #3498db",
                                  borderRadius: "50%",
                                  animation: "spin 1s linear infinite",
                                }}
                              ></div>
                              <span>正在回复...</span>
                            </div>
                          ) : (
                            item.content
                          )}
                        </div>

                        {/* 用户头像放在消息右侧 */}
                        {item.role === "user" && (
                          <Avatar
                            icon={<UserOutlined />}
                            style={{
                              marginLeft: "8px",
                              backgroundColor: "#1890ff",
                            }}
                          />
                        )}
                      </List.Item>
                    )}
                  />
                  <div ref={messageEndRef} />
                </div>

                {/* 输入区域 */}
                <div
                  style={{
                    display: "flex",
                    gap: "8px",
                    position: "absolute",
                    bottom: 50,
                    left: 50,
                  }}
                >
                  <Button
                    icon={<AudioOutlined />}
                    onClick={toggleVoiceRecognition}
                    loading={isListening}
                    style={{
                      borderRadius: "50%",
                      width: 48,
                      height: 48,
                      minWidth: 0,
                      backgroundColor: isListening ? "#ff4d4f" : "#1890ff",
                      color: "white",
                      transition: "all 0.3s",
                      boxShadow: isListening ? "0 0 15px #ff4d4f" : "none",
                    }}
                  />
                  <Popover
                    open={showEmojiPanel}
                    onOpenChange={setShowEmojiPanel}
                    content={
                      <div
                        style={{
                          padding: "10px",
                          display: "flex",
                          flexWrap: "wrap",
                          gap: "5px",
                          maxWidth: "300px",
                        }}
                      >
                        {emojis.map((emoji, index) => (
                          <Button
                            key={index}
                            onClick={() => addEmojiToInput(emoji)}
                            style={{
                              fontSize: "20px",
                              width: "40px",
                              height: "40px",
                              minWidth: 0,
                              padding: 0,
                            }}
                          >
                            {emoji}
                          </Button>
                        ))}
                      </div>
                    }
                    trigger="click"
                  >
                    <Button
                      icon={<SmileOutlined />}
                      style={{
                        borderRadius: "50%",
                        width: 48,
                        height: 48,
                        minWidth: 0,
                        backgroundColor: "#1890ff",
                        color: "white",
                      }}
                    />
                  </Popover>
                  <Input
                    value={inputText}
                    onChange={(e) => setInputText(e.target.value)}
                    onPressEnter={handleSendMessage}
                    placeholder="请输入消息..."
                    style={{
                      width: "500px",
                      flex: 1,
                      borderRadius: "20px",
                      padding: "8px 16px",
                    }}
                  />
                  <Button
                    icon={<SendOutlined />}
                    onClick={handleSendMessage}
                    style={{
                      width: "50px",
                      height: "50px",
                      borderRadius: "50%",
                      backgroundColor: "#1890ff",
                      border: "none",
                    }}
                  />
                </div>
              </div>
              {/* 添加视频元素 */}
              <video
                ref={videoRef}
                src="/videos/rBsCHWRkJ26ADw9GAWlEkvvYZ8w683.mp4"
                style={{
                  margin: "auto",
                  width: "90%",
                  height: "90%",
                  objectFit: "contain",
                  borderRadius: 4,
                  display: flagshow ? "block" : "none",
                }}
                controls
                autoPlay
                muted
                loop
              />
              {/* 弹幕组件 */}
              {videoSize.width > 0 && flagshow && flag && (
                <Barrage flag={flag} videoRef={videoRef} />
              )}
            </div>
            <div
              style={{
                position: "absolute",
                bottom: 50,
                right: 200,
                width: "100px",
                height: "50px",
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
              }}
            >
              <img
                style={{ margin: "10px" }}
                src={isSpeend1 ? icon11 : icon1}
                alt=""
                onClick={changesicon1}
              />
              <img
                style={{ margin: "10px" }}
                src={isSpeend2 ? icon22 : icon2}
                alt=""
                onClick={changesicon2}
              />
              <img
                style={{ margin: "10px" }}
                src={isSpeend3 ? icon33 : icon3}
                alt=""
                onClick={changesicon3}
              />
            </div>
          </div>
        </div>

        {/* 底部叠加图片 */}
        <div
          className={style[`${isSpeend ? "bd-day" : "bd-night"}`]}
          style={{
            width: "100%",
            position: "fixed",
            left: 0,
            bottom: 0,
            height: 80,
            zIndex: 10,
          }}
        ></div>
      </div>
    </div>
  );
};
export default Numpeo;
